#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: deprecated_app.py
# @time: 2021/4/19 20:14
# @desc:
import json
from fastapi import APIRouter, Request

from models.queryModels import HistoryClampSceneModel, StandardClampSceneModel, HistoryClampStandardClamp, HistoryPartStandardPart, StandardPartParameterModel, HistoryPartParameterModel
from models.responseModels import ResponseDict, ResponseBool
from utils.mongo_tools import update_mongo_value, retrieve_one_mongo_value, create_one_mongo_value, retrieve_all_mongo_values, delete_mongo_value_by_filter_condition
from views.configs import *

relation_router = APIRouter(
    # prefix="/api/parammodel",
    prefix="/api/relation",
    tags=["relation"],
)


@relation_router.post("/v1/history_clamp_scene")
async def bind_history_clamp_scene(request: Request, queryModel: HistoryClampSceneModel):
    """
    绑定历史夹具和场景的编号，注意此时一定是未绑定关系。

    - :return:
    """
    scene = retrieve_one_mongo_value(
        number=queryModel.scene_number,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )[0]
    if "historyClamp" not in scene.keys():
        scene["historyClamp"] = []
    if type(scene["historyClamp"]) is list:
        scene["historyClamp"].append(queryModel.history_clamp_number)
    else:
        scene["historyClamp"] = []
        scene["historyClamp"].append(queryModel.history_clamp_number)

    await request.app.state.redis.set(scene["number"], json.dumps(scene))
    updateInfo = {"$set": scene}
    update_mongo_value(
        filter_condition={"number": queryModel.scene_number},
        new_value=updateInfo,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )
    model = {"data": {queryModel.scene_number: queryModel.history_clamp_number}, "status": 1}
    return model


@relation_router.delete("/v1/history_clamp_scene")
async def delete_history_clamp_scene(request: Request, queryModel: HistoryClampSceneModel):
    """
    删除标准夹具和场景的关系，注意此时一定是已绑定关系。

    - :param queryModel:
    - :return:
    """
    scene = retrieve_one_mongo_value(
        number=queryModel.scene_number,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )[0]
    scene["historyClamp"].remove(queryModel.history_clamp_number)

    await request.app.state.redis.set(scene["number"], json.dumps(scene))

    updateInfo = {"$set": scene}
    update_mongo_value(
        filter_condition={"number": queryModel.scene_number},
        new_value=updateInfo,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )
    model = {"data": True, "status": 1}
    return model


@relation_router.get("/v1/history_clamp_scene")
async def retrieve_history_clamp_scene(request: Request, scene_number: str, history_clamp_number: str):
    """
    查询历史夹具和场景的关系，若已绑定返回True，否则返回False。

    - :param scene_number:
    - :param history_clamp_number:
    - :return:
    """
    try:
        scene = await request.app.state.redis.get(scene_number)
        scene = json.loads(scene)
    except:
        scene = retrieve_one_mongo_value(
            number=scene_number,
            database_name=MONGO_DATABASE_NAME,
            collection_name=SCENE_COLLECTION,
        )[0]
        await request.app.state.redis.set(scene_number, json.dumps(scene))

    try:
        if history_clamp_number in scene["historyClamp"]:
            model = {"data": True}
        else:
            model = {"data": False}
    except:
        model = {"data": False}
    model["status"] = 1
    return model


@relation_router.post("/v1/standard_clamp_scene")
async def bind_standard_clamp_scene(queryModel: StandardClampSceneModel):
    """
    绑定标准夹具和场景的编号，注意此时一定是未绑定关系。

    - :return:
    """
    scene = retrieve_one_mongo_value(
        number=queryModel.scene_number,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )[0]
    if "standardClamp" not in scene.keys():
        scene["standardClamp"] = []
    if type(scene["standardClamp"]) is list:
        scene["standardClamp"].append(queryModel.standard_clamp_number)
    else:
        scene["standardClamp"] = []
        scene["standardClamp"].append(queryModel.standard_clamp_number)
    updateInfo = {"$set": scene}
    update_mongo_value(
        filter_condition={"number": queryModel.scene_number},
        new_value=updateInfo,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )
    model = {"data": {queryModel.scene_number: queryModel.standard_clamp_number}, "status": 1}
    return model


@relation_router.delete("/v1/standard_clamp_scene")
async def delete_standard_clamp_scene(queryModel: StandardClampSceneModel):
    """
    删除标准夹具和场景的关系，注意此时一定是已绑定关系。

    - :param queryModel:
    - :return:
    """
    scene = retrieve_one_mongo_value(
        number=queryModel.scene_number,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )[0]
    scene["standardClamp"].remove(queryModel.standard_clamp_number)
    updateInfo = {"$set": scene}
    update_mongo_value(
        filter_condition={"number": queryModel.scene_number},
        new_value=updateInfo,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )
    model = {"data": True, "status": 1}
    return model


@relation_router.get("/v1/standard_clamp_scene")
async def retrieve_standard_clamp_scene(scene_number: str, standard_clamp_number: str):
    """
    查询标准夹具和场景的关系，若已绑定返回True，否则返回False。

    - :param scene_number:
    - :param standard_clamp_number:
    - :return:
    """
    scene = retrieve_one_mongo_value(
        number=scene_number,
        database_name=MONGO_DATABASE_NAME,
        collection_name=SCENE_COLLECTION,
    )[0]
    try:
        if standard_clamp_number in scene["standardClamp"]:
            model = {"data": True}
        else:
            model = {"data": False}
    except:
        model = {"data": False}
    model["status"] = 1
    return model


@relation_router.post("/v1/clamp_relation", response_model=ResponseDict)
async def bind_clamp(queryModel: HistoryClampStandardClamp):
    """
    绑定历史夹具和标准夹具的编号
    - :return:
    """
    model = {"data": {}}
    try:
        create_one_mongo_value(
            {
                "history_clamp_number": queryModel.history_clamp_number,
                "standard_clamp_number": queryModel.standard_clamp_number,
            },
            database_name=MONGO_DATABASE_NAME,
            collection_name="01_03_relation",
        )
        model["data"] = {queryModel.history_clamp_number: queryModel.standard_clamp_number}
        model["status"] = 1
    except:
        model["status"] = 0
    return model


@relation_router.get("/v1/clamp_relation", response_model=ResponseBool)
async def retrieve_clamp_relation(history_clamp_number: str, standard_clamp_number: str):
    """
    查询历史夹具和标准夹具的关系，若已绑定返回True，否则返回False。

    - :return:
    """
    model = {}
    try:
        result = retrieve_all_mongo_values(
            {
                "history_clamp_number": history_clamp_number,
                "standard_clamp_number": standard_clamp_number,
            },
            database_name=MONGO_DATABASE_NAME,
            collection_name="01_03_relation",
        )
        if len(result) > 0:
            model["data"] = True
        else:
            model["data"] = False

        model["status"] = 1
    except:
        model["status"] = 0
    return model


@relation_router.delete("/v1/clamp_relation", response_model=ResponseDict)
async def delete_clamp_relation(queryModel: HistoryClampStandardClamp):
    """
    取消绑定历史夹具和标准夹具
    - :return:
    """
    model = {}
    try:
        model["data"] = {queryModel.history_clamp_number: queryModel.standard_clamp_number}
        delete_mongo_value_by_filter_condition(
            {
                "history_clamp_number": queryModel.history_clamp_number,
                "standard_clamp_number": queryModel.standard_clamp_number,
            },
            database_name=MONGO_DATABASE_NAME,
            collection_name="01_03_relation",
        )
        model["msg"] = "success"
        model["status"] = 1
    except:

        model["status"] = 0
    return model


@relation_router.post("/v1/history_standard_part_relation", response_model=ResponseDict)
async def bind_history_standard_part(queryModel: HistoryPartStandardPart):
    """
    绑定历史零件和标准零件的编号
    - :return:
    """
    model = {}
    try:
        create_one_mongo_value(
            {
                "history_part_number": queryModel.history_part_number,
                "standard_part_number": queryModel.standard_part_number,
            },
            database_name=MONGO_DATABASE_NAME,
            collection_name="02_04_relation",
        )
        model["msg"] = "success"
        model["status"] = 1
        model["data"] = {queryModel.history_part_number: queryModel.standard_part_number}
    except:

        model["status"] = 0
    return model


@relation_router.get("/v1/history_standard_part_relation", response_model=ResponseBool)
async def retrieve_history_standard_part_relation(history_part_number: str, standard_part_number: str):
    """
    查询历史零件和标准零件的关系，若已绑定返回True，否则返回False。

    - :return:
    """
    model = {}
    try:
        result = retrieve_all_mongo_values(
            {
                "history_part_number": history_part_number,
                "standard_part_number": standard_part_number,
            },
            database_name=MONGO_DATABASE_NAME,
            collection_name="02_04_relation",
        )
        if len(result) > 0:
            model["data"] = True
        else:
            model["data"] = False

        model["status"] = 1
    except:

        model["status"] = 0
    return model


@relation_router.delete("/v1/history_standard_part_relation", response_model=ResponseDict)
async def delete_history_standard_part_relation(queryModel: HistoryPartStandardPart):
    """
    取消绑定历史零件和标准零件

    - :return:
    """
    model = {}
    try:
        model["data"] = {queryModel.history_part_number: queryModel.standard_part_number}
        delete_mongo_value_by_filter_condition(
            {
                "history_part_number": queryModel.history_part_number,
                "standard_part_number": queryModel.standard_part_number,
            },
            database_name=MONGO_DATABASE_NAME,
            collection_name="02_04_relation",
        )
        model["status"] = 1
    except:
        model["status"] = 0
    return model


@relation_router.post("/v1/standard_parameter_part_relation", response_model=ResponseDict)
async def bind_standard_parameter_part(queryModel: StandardPartParameterModel):
    """
    绑定标准零件和参数化模型的编号

    - :return:
    """
    model = {}
    try:
        create_one_mongo_value(
            {
                "standard_part_number": queryModel.standard_part_number,
                "parameter_number": queryModel.parameter_number
            },
            database_name="do_center",
            collection_name="04_05_relation",
        )

        model["status"] = 1
        model["data"] = {queryModel.standard_part_number: queryModel.parameter_number}
    except:

        model["status"] = 0
    return model


@relation_router.get("/v1/standard_parameter_part_relation", response_model=ResponseBool)
async def retrieve_standard_parameter_part_relation(standard_part_number: str, parameter_number: str):
    """
    查询标准零件和参数化模型的关系，若已绑定返回True，否则返回False。

    - :return:
    """
    model = {}
    try:
        result = retrieve_all_mongo_values(
            {
                "standard_part_number": standard_part_number,
                "parameter_number": parameter_number
            },
            database_name="do_center",
            collection_name="04_05_relation",
        )
        if len(result) > 0:
            model["data"] = True
        else:
            model["data"] = False

        model["status"] = 1
    except:

        model["status"] = 0
    return model


@relation_router.delete("/v1/standard_parameter_part_relation", response_model=ResponseDict)
async def delete_standard_parameter_part_relation(queryModel: StandardPartParameterModel):
    """
    取消绑定标准零件和参数化模型

    - :return:
    """
    model = {}
    try:
        model["data"] = {queryModel.standard_part_number: queryModel.parameter_number}
        delete_mongo_value_by_filter_condition(
            {
                "standard_part_number": queryModel.standard_part_number,
                "parameter_number": queryModel.parameter_number,
            },
            database_name="do_center",
            collection_name="04_05_relation",
        )

        model["status"] = 1
    except:

        model["status"] = 0
    return model


@relation_router.post("/v1/history_parameter_part_relation", response_model=ResponseDict)
async def bind_standard_parameter_part(queryModel: HistoryPartParameterModel):
    """
    绑定历史零件和参数化模型的编号

    - :return:
    """
    model = {}
    try:
        create_one_mongo_value(
            {
                "history_part_number": queryModel.history_part_number,
                "parameter_number": queryModel.parameter_number
            },
            database_name="do_center",
            collection_name="02_05_relation",
        )

        model["status"] = 1
        model["data"] = {queryModel.history_part_number: queryModel.parameter_number}
    except:

        model["status"] = 0
    return model


@relation_router.get("/v1/history_parameter_part_relation", response_model=ResponseBool)
async def retrieve_history_parameter_part_relation(history_part_number: str, parameter_number: str):
    """
    查询历史零件和参数化模型的关系，若已绑定返回True，否则返回False。

    - :return:
    """
    model = {}
    try:
        result = retrieve_all_mongo_values(
            {
                "history_part_number": history_part_number,
                "parameter_number": parameter_number
            },
            database_name="do_center",
            collection_name="02_05_relation",
        )
        if len(result) > 0:
            model["data"] = True
        else:
            model["data"] = False

        model["status"] = 1
    except:

        model["status"] = 0
    return model


@relation_router.delete("/v1/history_parameter_part_relation", response_model=ResponseDict)
async def delete_history_parameter_part_relation(queryModel: HistoryPartParameterModel):
    """
    取消绑定历史零件和参数化模型
    - :return:
    """
    model = {}
    try:
        model["data"] = {queryModel.history_part_number: queryModel.parameter_number}
        delete_mongo_value_by_filter_condition(
            {
                "history_part_number": queryModel.history_part_number,
                "parameter_number": queryModel.parameter_number,
            },
            database_name="do_center",
            collection_name="02_05_relation",
        )

        model["status"] = 1
    except:

        model["status"] = 0
    return model


@relation_router.post("/v2/clamp_relation", response_model=ResponseDict)
async def bind_clamp_v2(request: Request, queryModel: HistoryClampStandardClamp):
    """
    绑定历史夹具和标准夹具的编号
    - :return:
    """
    model = {"data": {}}
    try:
        data = retrieve_one_mongo_value(
            number=queryModel.history_clamp_number,
            database_name=MONGO_DATABASE_NAME,
            collection_name=HISTORY_CLAMP_COLLECTION,
        )[0]
        data["related"] = {}
        data["related"]["standardClamp"] = queryModel.standard_clamp_number
        await request.app.state.redis.set(queryModel.history_clamp_number, json.dumps(data))
        updateInfo = {"$set": data}
        update_mongo_value(
            filter_condition={"number": queryModel.history_clamp_number},
            new_value=updateInfo,
            database_name=MONGO_DATABASE_NAME,
            collection_name=HISTORY_CLAMP_COLLECTION,
        )
        model["data"] = {queryModel.history_clamp_number: queryModel.standard_clamp_number}
        model["status"] = 1
    except:
        model["status"] = 0
    return model


@relation_router.get("/v2/clamp_relation")
async def retrieve_clamp_relation_v2(request: Request, history_clamp_number: str, standard_clamp_number: str):
    """
    查询历史夹具和标准夹具的关系，若已绑定返回True，否则返回False。

    - :return:
    """
    model = {"status": 1}

    try:
        history_clamp = await request.app.state.redis.get(history_clamp_number)
        original_data = json.loads(history_clamp)
    except:
        # if reach here then means no data in redis. Now go to mongo.
        original_data = retrieve_one_mongo_value(history_clamp_number, database_name=MONGO_DATABASE_NAME, collection_name=HISTORY_CLAMP_COLLECTION)[0]
        # then add it into redis
        await request.app.state.redis.set(history_clamp_number, json.dumps(original_data))
    try:
        if original_data["related"]["standardClamp"] == standard_clamp_number:
            model["data"] = True
            return model
    except:
        pass
    model["data"] = False
    return model


@relation_router.delete("/v2/clamp_relation")
async def delete_clamp_relation_v2(request: Request, queryModel: HistoryClampStandardClamp):
    """
    - 取消绑定历史夹具和标准夹具。
    - 思路：先去redis里面根据request里历史夹具的number去查询该条历史夹具的数据，查看里面的standardClamp是否等于request里的数据。
    - 其实不用这样，这个接口过来的数据肯定是绑定在一起的。直接更新mongo和redis里对应历史夹具的绑定的标准夹具就好了。

    - :return:
    """
    model = {}
    try:
        update_mongo_value(
            filter_condition={"number": queryModel.history_clamp_number},
            new_value={"$set": {"related": {"standardClamp": []}}},
            database_name=MONGO_DATABASE_NAME,
            collection_name=HISTORY_CLAMP_COLLECTION,
        )

        data = retrieve_one_mongo_value(queryModel.history_clamp_number, database_name=MONGO_DATABASE_NAME, collection_name=HISTORY_CLAMP_COLLECTION)[0]
        await request.app.state.redis.set(queryModel.history_clamp_number, json.dumps(data))
        model["data"] = True
        model["status"] = 1
    except:
        model["data"] = False
        model["status"] = 0

    return model
